import Vue from 'vue'
import VueRouter from 'vue-router'

// 插件必要要声明 使用插件
Vue.use(VueRouter)

// 引入路由组件
import Home from '@/views/Home/Home.vue'
import Search from '@/views/Search/Search.vue'
import Login from '@/views/Login/Login.vue'
import Register from '@/views/Register/Register.vue'

// 重写vue-router上的$router.push和replace方法
// 1.先把VueRouter原型对象上的push|replace保存一份
let origionPush = VueRouter.prototype.push
let origionReplace = VueRouter.prototype.replace
// 2.重写push|replace
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    origionPush.call(this, location, resolve, reject)
  } else {
    origionPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    origionReplace.call(this, location, resolve, reject)
  } else {
    origionReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

// 配置路由，并向外暴露
export default new VueRouter({
  routes: [
    {
      path: '/',
      redirect: '/home',
      // 提供给父组件来判断是否显示此组件
      meta: { show: true }
    },
    {
      path: '/home',
      component: Home,
      meta: { show: true }
    },
    {
      // :kw 为动态参数名称，占位符，用于搜索时传入输入框的字符串参数
      // kw后面的？代表params参数可传可不传
      path: '/search/:kw?',
      component: Search,
      meta: { show: true },
      name: 'search'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    }
  ]
})
